import axios from 'axios'
import { ResultCode } from '@/config/http.js'

const Axios = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  timeout: ResultCode.TIMEOUT
  // withCredentials: true // 跨域时候允许携带凭证
})

// 请求拦截器
Axios.interceptors.request.use(
  (config) => {
    let Authorization = ''

    if (config.headers.Authorization) {
      Authorization = config.headers.Authorization
    } else {
      Authorization = `Bearer ${getToken()}`
    }

    return {
      ...config,
      headers: {
        ...config.headers,
        // 'trace-id': randomHash(),
        Authorization
      }
    }
  },
  (error) => Promise.reject(error)
)

// 响应拦截器
Axios.interceptors.response.use(
  (response) => {
    if (!response.data.code) {
      return response.data
    }
    return response.data
  },
  (error) => {
    if (!error.response.data) {
      return message.error('未知异常，请联系管理员！')
    }

    if (error.response.data.code === 403) {
      message.error('请求参数异常，请重新输入！')
    } else if (error.response.data.msg) {
      message.error(error.response.data.msg)
    }

    return Promise.reject(error)
  }
)

export default Axios
